import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_hi_cache/flutter_hi_cache.dart';
import 'package:get/get.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/pages/login/login_controller.dart';
import 'package:yysk_app/pages/login/login_page.dart';
import 'package:yysk_app/pages/nft_pages/setting/modify_password.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_exchange_psw.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_controller.dart';
import 'package:yysk_app/utils/check_for_updates.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';
import 'package:yysk_app/widget/card_item_widget.dart';
import 'package:yysk_app/widget/custom_app_bar2.dart';
import 'package:yysk_app/widget/lazy_network_image.dart';
import 'package:yysk_app/widget/list_route_tile.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_abount_us.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_info.dart';
import 'package:yysk_app/pages/nft_pages/setting/setting_real_name_auth_page.dart';
import 'package:yysk_app/widget/button_widget.dart';
import 'package:yysk_app/utils/dialog_widget.dart';
import 'package:yysk_app/widget/input_widget.dart';
import 'package:yysk_app/widget/image_asset_widget.dart';
import 'package:yysk_app/pages/nft_pages/wallet_pages/manage_bank/manage_bank_type_page.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart';
import 'package:oktoast/oktoast.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image/image.dart' as img;

class SettingPage extends GetView<SettingController> {
  static const String path = '/setting';
  SettingPage({super.key});

  final TextEditingController nickNameController = TextEditingController();
  final ImagePicker picker = ImagePicker();
  final GlobalController globalController = Get.find();

  @override
  Widget build(BuildContext context) {
    double top = MediaQuery.of(context).padding.top;
    return PopScope(
      canPop: false,
      child: Scaffold(
        resizeToAvoidBottomInset: false,

        bottomNavigationBar: BottomAppBar(
          padding: EdgeInsets.symmetric(horizontal: 24.px, vertical: 0),
          height: 88.px,
          color: Colors.transparent,
          child: Center(
            child: ButtonWidget(
              width: 322.px,
              height: 55.px,
              fontSize: 18.px,
              imageBg: 'static/images/btm.png',
              contentType: ContentType.other,
              colorStart: AppColors.fontColorGreenStartTab,
              colorEnd: AppColors.fontColorGreenEndTab,
              label: '退出',
              onPressed: () {
                showConfirmDialog(
                  context: context,
                  fontSize: 16,
                  message: '是否确认退出当前账号?',
                  actions: [
                    ActionModel(
                      label: '取消',
                      colorStart: AppColors.backgroundColorGreyF8,
                      colorEnd: AppColors.backgroundColorGreyF8,
                      fontColor: AppColors.fontColor,
                    ),
                    ActionModel(
                      label: '确定',
                      onPressed: () {
                        _logout();
                      },
                    ),
                  ],
                );
              },
            ),
          ),
        ),
        body: Stack(
          children: [
            SizedBox(
              width: context.width,
              child: ImageAssetWidget(
                width: 375.px,
                height: 270.px,
                imageUrl: 'static/images/setting_page_bg@2x.png',
              ),
            ),
            Container(
              color: Colors.transparent,
              padding: EdgeInsets.only(left: 16.px, top: top, right: 9.px),
              child: Column(
                children: [
                  CustomAppBar2(
                    title: '设置',
                    context: context,
                    beforBack: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  Obx(
                    () => Expanded(
                      child: ListView(
                        padding: EdgeInsets.only(top: 20),
                        children: [
                          CardItemWidget(
                            title: '基本信息',
                            child: Column(
                              children: [
                                ListRouteTile(
                                  title: '头像',
                                  route: '',
                                  trailing: SizedBox(
                                    width: 40,
                                    height: 40,
                                    child: LazyImage(
                                      imageUrl:
                                          '${globalController.user.value?.avatarImg}',
                                      borderRadius: 100,
                                    ),
                                  ),
                                  onTap: () {
                                    showConfirmDialog(
                                      context: context,
                                      message: '允许元宇时空访问相机相册权限',
                                      messages: ['为实现您图片的拍摄或上传'],
                                      actions: [
                                        ActionModel(
                                          label: '取消',
                                          colorStart:
                                              AppColors.backgroundColorGreyF8,
                                          colorEnd:
                                              AppColors.backgroundColorGreyF8,
                                          fontColor: AppColors.fontColor,
                                        ),
                                        ActionModel(
                                          label: '授权',
                                          onPressed: _uploadImage,
                                        ),
                                      ],
                                    );
                                  },
                                ),
                                ListRouteTile(
                                  title: '昵称',
                                  route: '',
                                  trailing: Text(
                                    '${globalController.user.value?.nickName ?? '--'} ',
                                    style: TextStyle(
                                      fontSize: 15.px,
                                      fontWeight: FontWeight.normal,
                                      color: AppColors.fontColorBlack
                                          .withOpacity(0.67),
                                    ),
                                  ),
                                  onTap: () {
                                    showConfirmDialog(
                                      context: context,
                                      inputCode: true,
                                      fontSize: 16,
                                      children: [
                                        InputWidget(
                                          hint: '请输入昵称',
                                          controller: nickNameController,
                                          maxLength: 10,
                                          inputType: TextInputType.name,
                                        ),
                                      ],
                                      actions: [
                                        ActionModel(label: '取消'),
                                        ActionModel(
                                          label: '确定',
                                          onPressed: () {
                                            controller.updateNickName(
                                              nickNameController.text,
                                            );
                                            nickNameController.text = '';
                                          },
                                        ),
                                      ],
                                    );
                                  },
                                ),
                                ListRouteTile(
                                  title: '注册账号',
                                  route: '',
                                  trailing: Text(
                                    '${globalController.user.value?.userTel ?? '--'} ',
                                    style: TextStyle(
                                      fontSize: 15.px,
                                      fontWeight: FontWeight.normal,
                                      color: AppColors.fontColorBlack
                                          .withOpacity(0.67),
                                    ),
                                  ),
                                ),
                                ListRouteTile(
                                  title: '实名认证',
                                  route: '',
                                  trailing: RichText(
                                    textAlign: TextAlign.center,
                                    text: TextSpan(
                                      text:
                                          (globalController.user.value?.isSm ??
                                                  false)
                                              ? '已实名'
                                              : '未实名',
                                      style: TextStyle(
                                        fontSize: 15.px,
                                        fontWeight: FontWeight.normal,
                                        color: AppColors.fontColorBlack
                                            .withOpacity(0.67),
                                      ),
                                      children: <InlineSpan>[
                                        TextSpan(text: ' '),
                                        WidgetSpan(
                                          alignment:
                                              PlaceholderAlignment.middle,
                                          child: Icon(
                                            Icons.arrow_forward_ios,
                                            color: AppColors.fontColorBlack
                                                .withValues(alpha: 0.67),
                                            size: 14.px,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  onTap: () {
                                    (globalController.user.value?.isSm ?? false)
                                        ? Get.toNamed(SettingRealNameInfo.path)
                                        : Get.toNamed(
                                          SettingRealNameAuthPage.path,
                                        );
                                  },
                                ),
                              ],
                            ),
                          ),
                          CardItemWidget(
                            title: '账户安全',
                            child: Column(
                              children: [
                                ListRouteTile(
                                  title: '登录密码',
                                  route: '',
                                  onTap: () {
                                    Get.toNamed(ModifyPassword.path);
                                  },
                                ),
                                ListRouteTile(
                                  title: '交易密码',
                                  route: '',
                                  onTap: () {
                                    Get.toNamed(ChangeExchangePassword.path);
                                  },
                                ),
                                ListRouteTile(
                                  title: '绑定银行卡',
                                  route: '',
                                  onTap: () {
                                    if (globalController.user.value!.isSm ==
                                        true) {
                                      Get.toNamed(ManageBankTypePage.path);
                                    } else {
                                      showConfirmDialog(
                                        context: context,
                                        fontSize: 16,
                                        message: '请先完成实名认证',
                                        actions: [
                                          ActionModel(
                                            label: '取消',
                                            colorStart:
                                                AppColors.backgroundColorGreyF8,
                                            colorEnd:
                                                AppColors.backgroundColorGreyF8,
                                            fontColor: AppColors.fontColor,
                                          ),
                                          ActionModel(
                                            label: '立即认证',
                                            onPressed: () {
                                              Get.toNamed(
                                                SettingRealNameAuthPage.path,
                                              );
                                            },
                                          ),
                                        ],
                                      );
                                    }
                                  },
                                ),
                              ],
                            ),
                          ),

                          CardItemWidget(
                            title: '其他',
                            child: Column(
                              children: [
                                ListRouteTile(
                                  title: '关于我们',
                                  route: '',
                                  onTap: () {
                                    Get.toNamed(AbountUsVC.path);
                                  },
                                ),
                                ListRouteTile(
                                  title: '当前版本',
                                  route: '',
                                  onTap: () {
                                    fetchVersionInfo().then((res) {
                                      chech_updata(
                                        res: res,
                                        context: Get.context!,
                                      ).then((res) {
                                        if (res) showToast('已经是最新版本');
                                      });
                                    });
                                  },
                                  trailing: RichText(
                                    text: TextSpan(
                                      text: 'v${controller.version}',
                                      style: TextStyle(
                                        fontSize: 15.px,
                                        fontWeight: FontWeight.normal,
                                        color: AppColors.fontColorBlack,
                                      ),
                                      children: <InlineSpan>[
                                        TextSpan(text: ' '),
                                        WidgetSpan(
                                          alignment:
                                              PlaceholderAlignment.middle,
                                          child: Icon(
                                            Icons.arrow_forward_ios,
                                            color: AppColors.fontColorBlack
                                                .withValues(alpha: 0.67),
                                            size: 14.px,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),

                                ListRouteTile(
                                  title: '清除缓存',
                                  route: '',
                                  onTap: () {
                                    showConfirmDialog(
                                      context: context,
                                      fontSize: 16,
                                      message: '您确定要清除缓存吗',
                                      actions: [
                                        ActionModel(
                                          label: '取消',
                                          colorStart:
                                              AppColors.backgroundColorGreyF8,
                                          colorEnd:
                                              AppColors.backgroundColorGreyF8,
                                          fontColor: AppColors.fontColor,
                                        ),
                                        ActionModel(
                                          label: '确定',
                                          onPressed: clearAppCache,
                                        ),
                                      ],
                                    );
                                  },
                                ),

                                ListRouteTile(
                                  title: '注销账号',
                                  route: '',
                                  onTap: () {
                                    controller.canCancelAccount(context);
                                  },
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _logout() {
    http.netFetch(
      ApiUrl.logout,
      success: (data) {
        showToast('退出成功！');
        HiCache.getInstance().remove(LoginController.boardingPassToken);
        Get.offAllNamed(LoginPage.path);
      },
    );
  }

  void _uploadImage() async {
    try {
      final XFile? image = await picker.pickImage(source: ImageSource.gallery);

      // 2. 获取腾讯云上传地址
      await _getUploadUrl().then((res) {
        //  _uploadToTencentCloud(res, File(image!.path));
        _uploadToTencentCloud(res, image!);
        debugPrint('腾讯云上传地址: $res');
      });

      // 3. 上传文件到腾讯云
      // await _uploadToTencentCloud(uploadUrl, File(image!.path));
    } catch (e) {
      debugPrint('图片处理出错：${e.toString()}');
    }
  }

  //图片颜色校正、压缩
  Future<Uint8List> correctColor(XFile file) async {
    final image = img.decodeImage(await file.readAsBytes());
    final resized = img.copyResize(image!, width: 1024); // 限制最大宽度
    // final processed = img.copyResize(
    //   img.adjustColor(
    //     image!,
    //     gamma: 0.9,
    //     saturation: 0.8
    //   ),
    //   interpolation: img.Interpolation.cubic
    // );
    // return img.encodeJpg(processed, quality: 95);
    // return img.encodeJpg(image!, quality: 85
    //   // img.adjustColor(image!,
    //   //   gamma: 0.9,  // 降低绿色通道强度
    //   //   saturation: 0.8
    //   // )
    // );
    return img.encodePng(resized);
  }

  //获取上传图片链接
  Future<String> _getUploadUrl() async {
    int timestampInSeconds = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    try {
      final response = await http.netFetch<dynamic>(
        ApiUrl.getUploadUrl,
        method: Method.post,
        params: {'key': '$timestampInSeconds.png'},
      );

      if (response?.code == 200) {
        controller.avatarImg.value = response?.data.split('?')[0];
        debugPrint('渠道图片地址: ${controller.avatarImg.value}');
        return response?.data;
      }
      return response?.data;
    } catch (e) {
      debugPrint('获取上传地址出错: ${e.toString()}');
      rethrow; // 重新抛出异常，让外层处理
    }
  }

  //上传图片
  Future<bool> _uploadToTencentCloud(String url, XFile file) async {
    try {
      // final fileBytes = await file.readAsBytes();
      final fileBytes = await correctColor(file);

      // 创建独立的Dio实例，避免全局配置污染
      final dio = Dio(
        BaseOptions(
          responseType: ResponseType.plain, // 明确接收文本响应
          validateStatus: (status) => true, // 处理所有状态码
        ),
      );

      final response = await dio
          .put<String>(
            // 指定返回类型为String
            url,
            data: fileBytes,
            options: Options(
              headers: {
                'Content-Type': _getMimeType(file.name),
                'Content-Length': fileBytes.length.toString(),
              },
            ),
          )
          .then((res) {
            //  debugPrint('上传响应原始数据222: ${res}========');
            controller.updateAvatarImg(() {});
          });

      // debugPrint('上传响应原始数据: ${response}========');

      // 根据状态码判断成功，而不是响应体内容
      if (response == null) {
        // 更新用户信息
        globalController.getUserInfo();
        return true;
      }

      // 处理其他状态码
      throw DioException(
        requestOptions: response.requestOptions,
        response: response,
        error: '上传失败，状态码：${response.statusCode}',
      );
    } on DioException catch (e) {
      // 统一错误处理
      debugPrint('上传错误详情: ${e.message}');
      if (e.response != null) {
        debugPrint('错误响应头: ${e.response?.headers}');
        debugPrint('错误响应体: ${e.response?.data}');
      }
      showToast('上传失败: ${e.message ?? "未知错误"}');
      return false;
    }
  }

  String _getMimeType(String filename) {
    final ext = filename.split('.').last.toLowerCase();
    switch (ext) {
      case 'png':
        return 'image/png';
      case 'jpg':
        return 'image/jpeg';
      case 'jpeg':
        return 'image/jpeg';
      case 'gif':
        return 'image/gif';
      case 'webp':
        return 'image/webp';
      default:
        return 'application/octet-stream'; // 更通用的二进制类型
    }
  }

  Future<void> clearAppCache() async {
    final tempDir = await getTemporaryDirectory();
    final cacheDir = await getApplicationDocumentsDirectory();

    // 删除临时目录中的所有文件
    await deleteDirectoryContents(tempDir);

    // 删除应用文档目录中的缓存文件（假设缓存文件存储在'cache'子目录中）
    final cacheSubDir = Directory('${cacheDir.path}/cache');
    if (await cacheSubDir.exists()) {
      await deleteDirectoryContents(cacheSubDir);
    }
    showToast('清除成功');
  }

  Future<void> deleteDirectoryContents(Directory dir) async {
    if (await dir.exists()) {
      await for (final fileSystemEntity in dir.list()) {
        if (fileSystemEntity is File) {
          await fileSystemEntity.delete();
        } else if (fileSystemEntity is Directory) {
          await deleteDirectoryContents(fileSystemEntity);
          await fileSystemEntity.delete();
        }
      }
    }
  }
}
